import { defineStore } from 'pinia'
import { filesApi } from '../api/files.js'

export const useFilesStore = defineStore('files', {
	state: () => ({
		fileTree: [],
		currentFolder: null,
		lastUpdateTime: null,
		isLoading: false
	}),

	actions: {
		async fetchFileTree() {
			try {
				// 显示加载动画
				this.isLoading = true
				uni.showLoading({
					title: '加载中...',
					mask: true
				})

				console.log('开始获取文件树')
				console.time('请求耗时')

				const startTime = Date.now()
				// const testDbRes = await filesApi.testDb()
				// console.log('testDbRes', testDbRes)
				const response = await filesApi.getFileTree()
				const endTime = Date.now()

				console.log(`网络请求耗时: ${endTime - startTime}ms`)
				console.timeEnd('请求耗时')

				if (response.success) {
					console.time('数据处理耗时')
					this.fileTree = response.data
					this.lastUpdateTime = Date.now()

					// 保存到本地存储
					console.timeEnd('数据处理耗时')
				}

				// 隐藏加载动画
				this.isLoading = false
				uni.hideLoading()

				return response.data
			} catch (error) {
				this.isLoading = false
				uni.hideLoading()
				console.error('获取文件树失败:', error)
				uni.showToast({
					title: '获取文件列表失败',
					icon: 'none'
				})
				return []
			}
		}
	}
})
